﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Sistema_Test_OnLine.Model;
using Sistema_Test_OnLine.Logic;
using System.Security.Cryptography;
using System.Text;
using System.Net;
using System.Net.Mail;
using System.IO;

namespace Sistema_Test_OnLine.Presentacion
{
    public partial class Recuperar_pass : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        public static string GetMD5(string str)
        {
            MD5 md5 = MD5CryptoServiceProvider.Create();
            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] stream = null;
            StringBuilder sb = new StringBuilder();
            stream = md5.ComputeHash(encoding.GetBytes(str));
            for (int i = 0; i < stream.Length; i++) sb.AppendFormat("{0:x2}", stream[i]);
            return sb.ToString();
        }

        
        protected void Enviar_pass_Click(object sender, EventArgs e)
        {
            String newpass = GetRandomString().Substring(1, 5);
            String pass = newpass;
            newpass = GetMD5(newpass);
            try
            {
                String criterio1 = "password = " + "'" + newpass + "'";
                String criterio2 = "correo = " + "'" + TextBox11.Text + "'";

                if (Facade.upUsers(criterio1, criterio2))
                {
                    MailMessage oMsg = new MailMessage("sistematestonline@gmail.com", TextBox11.Text);
                    oMsg.Subject = "Contraseña";
                    oMsg.Body = pass;
                    SmtpClient oClient = new SmtpClient("smtp.gmail.com");
                    oClient.Credentials = new System.Net.NetworkCredential("sistematestonline@gmail.com", "testonline");
                    oClient.EnableSsl = true;
                    oClient.Send(oMsg);
                    Label2.Text = "Su pass fue enviado a su correo...";
                }
                else Label2.Text = "El correo ingresado no esta registrado";
            }
            catch
            {
                Label2.Text = "Error al enviar pass";
            }
        }

        public static string GetRandomString()
        {
            string path =Path.GetRandomFileName();
            path = path.Replace(".", ""); // Remove period.
            return path;
        }
    }
}